<template>
  <div class="page-container">
    <h2>新增图文课程</h2>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="form-card">
      <el-form-item label="商品信息" prop="goodsInfo">
        <el-input v-model="formData.goodsInfo" type="textarea" :rows="3" placeholder="请输入商品详细信息" />
      </el-form-item>
      <el-form-item label="商品价格" prop="goodsPrice">
        <el-input-number v-model="formData.goodsPrice" :min="0" :precision="2" style="width: 100%" />
      </el-form-item>
      <el-form-item label="销量" prop="salesNum">
        <el-input-number v-model="formData.salesNum" :min="0" />
      </el-form-item>
      <el-form-item label="商品状态" prop="goodsState">
        <el-radio-group v-model="formData.goodsState">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { goodsApi } from '@/api/goods'

const formRef = ref()
const submitting = ref(false)

const formData = reactive({
  goodsInfo: '',
  goodsPrice: 0,
  salesNum: 0,
  goodsState: 1
})

const formRules = {
  goodsInfo: [{ required: true, message: '请输入商品信息', trigger: 'blur' }],
  goodsPrice: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  goodsState: [{ required: true, message: '请选择商品状态', trigger: 'change' }]
}

const handleReset = () => {
  Object.assign(formData, { goodsInfo: '', goodsPrice: 0, salesNum: 0, goodsState: 1 })
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    await goodsApi.addGoods(formData)
    ElMessage.success('新增成功')
    handleReset()
  } catch (e) {
    if (e !== false) ElMessage.error('新增失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.page-container { padding: 20px; }
.form-card { max-width: 600px; }
</style>


